package com.atguigu.gmall.all.service.impl;

import com.atguigu.gmall.all.service.ItemService;

import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {


    @Autowired
    private ProductFeignClient productFeignClient;




    @Override
    public List<Map> getBaseCategoryList() {
        List<Map> listMap = new ArrayList<>();
        List<BaseCategoryView> baseCategoryList = productFeignClient.getBaseCategoryList();
        Map<Long, List<BaseCategoryView>> categoryMap = baseCategoryList.stream().collect(Collectors.groupingBy((baseCategoryView) -> {
            return baseCategoryView.getCategory1Id();
        }));
        int index = 1;
        for(Map.Entry<Long,List<BaseCategoryView>> firstmap : categoryMap.entrySet()){
            Long category1Id = firstmap.getKey();
            List<BaseCategoryView> category1Views = firstmap.getValue();
            Map<String,Object> category1Map = new HashMap<>();

            category1Map.put("index",index++);
            category1Map.put("categoryName",category1Views.get(0).getCategory1Name());
            category1Map.put("categoryId",category1Id);
            Map<Long, List<BaseCategoryView>> category2ViewsList = category1Views.stream().collect(Collectors.groupingBy((baseCategoryView) -> {
                return baseCategoryView.getCategory2Id();
            }));
            List secondListMap = new ArrayList();
          for(Map.Entry<Long, List<BaseCategoryView>> secondMap : category2ViewsList.entrySet()){
              Long category2Id = secondMap.getKey();
              List<BaseCategoryView> category2Views = secondMap.getValue();
              Map<String,Object> category2Map = new HashMap<>();
              category2Map.put("categoryId",category2Id);
              category2Map.put("categoryName",category2Views.get(0).getCategory2Name());
              secondListMap.add(category2Map);
              List thirdListMap = new ArrayList();
              category2Views.stream().forEach((category3Views)->{
                  Map<String,Object> thirdMap = new HashMap<>();
                  thirdMap.put("categoryId",category3Views.getCategory3Id());
                  thirdMap.put("categoryName",category3Views.getCategory3Name());
                  thirdListMap.add(thirdMap);
              });
              category2Map.put("categoryChild",thirdListMap);
          }
            category1Map.put("categoryChild",secondListMap);
            listMap.add(category1Map);
        }

        return listMap;
    }


}
